<template>
  <div class="create-post-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="right" label-width="100px" class="territory-form">
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="CODE" prop="code">
            <el-input v-model="postForm.code" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="内部用户" prop="indoorid">
            <el-select
              v-model="postForm.indoorid"
              filterable
              remote
              reserve-keyword
              clearable
              placeholder="请输入内部用户code"
              :remote-method="remoteInternals"
              :loading="loading"
              style="width:100%"
            >
              <el-option
                v-for="item in internalOptions"
                :key="item.id"
                :label="`${item.code} - ${item.name}`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="上级" prop="superior">
            <el-select
              v-model="postForm.superior"
              filterable
              remote
              reserve-keyword
              clearable
              placeholder="请输入上级code"
              :remote-method="remoteSuperiors"
              :loading="loading"
              style="width:100%"
            >
              <el-option
                v-for="item in superiorOptions"
                :key="item.id"
                :label="`${item.code} - ${item.name}`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="主岗位" prop="mainjobs">
            <el-switch v-model="postForm.mainjobs" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt30">
        <el-col :span="18" :offset="3">
          <el-form-item>
            <el-button type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  getTerritoriesList,
  findTerritory,
  editTerritory,
  addTerritory
} from '@/api/territories'

const defaultForm = {
  id: undefined,
  code: '',
  indoorid: '',
  indoorName: '',
  superior: '',
  superiorName: '',
  mainjobs: ''
}

export default {
  name: 'TerritoryForm',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      internalOptions: [],
      superiorOptions: [],
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        code: [
          { required: true, message: '请输入CODE', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' }
        ],
        indoorid: [
          { required: true, message: '请选择内部用户', trigger: 'change' }
        ],
        superior: [
          { required: true, message: '请选择内部用户', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
  },
  methods: {
    remoteInternals(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          findTerritory({ code: query }).then(response => {
            const { data } = response
            // console.log(data)
            this.internalOptions = data
          }).catch(err => {
            console.log(err)
          })
        }, 200)
      } else {
        this.internalOptions = []
      }
    },
    remoteSuperiors(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          findTerritory({ code: query }).then(response => {
            const { data } = response
            // console.log(data)
            this.superiorOptions = data
          }).catch(err => {
            console.log(err)
          })
        }, 200)
      } else {
        this.superiorOptions = []
      }
    },
    fetchData(id) {
      getTerritoriesList({ id }).then(response => {
        const { data } = response
        // console.log(data)
        this.postForm.id = data[0].id
        this.postForm.code = data[0].code
        this.postForm.indoorid = data[0].indoorid
        this.postForm.indoorName = data[0].indoorName
        this.postForm.superior = data[0].superior
        this.postForm.superiorName = data[0].superiorName
        this.postForm.mainjobs = data[0].mainjobs
      }).catch(err => {
        console.log(err)
      })
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.isEdit) {
            editTerritory(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '编辑岗位成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          } else {
            addTerritory(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '添加岗位成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.postForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.create-post-container {
  position: relative;
  .territory-form {
    padding: 40px 140px;
  }
}
</style>
